Categories
React Native

React Native — Async Storage

Spread the love

React Native is a mobile development that’s based on React that we can use to do mobile development.

In this article, we’ll look at how to use it to create an app with React Native.

Async Storage

We can use the Async Storage library to store unencrypted data in our React Native app.

To install the library, we run:

yarn add @react-native-community/async-storage

Saving and Reading Data

Once we installed the library, we can import the library into our project and use it.

To do that, we write:

import React, { useState } from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

export default function App() {
  const [data, setData] = useState();

const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@storage_Key')
      if (value !== null) {
        setData(value)
      }
    } catch (e) {
      // error reading value
    }
  }

  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@storage_Key', value)
    } catch (e) {
      // saving error
    }
  }

  return (
    <View style={styles.container}>
      <Button title='save data' onPress={() => storeData('foo')}></Button>
      <Button title='read data' onPress={getData}></Button>
      <Text>{data}</Text>
    </View >
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We import the AsyncStorage object.

And we use them in the getData function to get data and the storeData function to store the data.

The AsyncStorage.getItem method gets the data by its key.

And AsyncStorage.setItem takes the key and the value for the key and save the data into storage.

We can also write and read objects as value.

For example, we can write:

import React, { useState } from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';

export default function App() {
  const [data, setData] = useState();

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@storage_Key')
      if (value !== null) {
        setData(JSON.parse(value))
      }
    } catch (e) {
      // error reading value
    }
  }

  const storeData = async () => {
    try {
      await AsyncStorage.setItem('@storage_Key', JSON.stringify({ foo: 'bar' }))
    } catch (e) {
      // saving error
    }
  }

  return (
    <View style={styles.container}>
      <Button title='save data' onPress={storeData}></Button>
      <Button title='read data' onPress={getData}></Button>
      <Text>{data.foo}</Text>
    </View >
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We called JSON.stringify to convert the object into a JSON string in storeData .

The getData function parses the stringified object that’s read from getItem with JSON.parse .

Remove Data

There’s also the removeItem method to remove data to remove an item by the key.

For example, we can write:

import React, { useState } from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
export default function App() {
  const [data, setData] = useState();
  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem('@storage_Key')
      setData(value);
    } catch (e) {
      // error reading value
    }
  }
  const storeData = async (value) => {
    try {
      await AsyncStorage.setItem('@storage_Key', value)
    } catch (e) {
      // saving error
    }
  }

  const removeValue = async () => {
    try {
      await AsyncStorage.removeItem('@storage_Key')
    } catch (e) {
      // remove error
    }
  }

  return (
    <View style={styles.container}>
      <Button title='save data' onPress={() => storeData('foo')}></Button>
      <Button title='read data' onPress={getData}></Button>
      <Button title='remove data' onPress={removeValue}></Button>
      <Text>{data}</Text>
    </View >
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

We call removeItem with the key in the removeValue function to remove an item with the given key.

Conclusion

The async storage library gives us an easy way to store data in an unencrypted manner with React Native.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *